/*
 Copyright (c) 2012, The Cinder Project
 All rights reserved.
 
 This code is designed for use with the Cinder C++ library, http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#pragma once

#include "cinder/DataSource.h"
#include "cinder/DataTarget.h"
#include "cinder/Exception.h"
#include "cinder/Stream.h"
#include "cinder/Utilities.h"

#include <iterator>
#include <string>
#include <vector>

namespace Json
{
    class Value;
}

namespace cinder {

	class JsonTree 
	{

	public:

		typedef std::vector<JsonTree>::const_iterator ConstIter;
		typedef std::vector<JsonTree>::iterator Iter;

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////

		typedef enum 
		{ 
			NODE_UNKNOWN, NODE_NULL, NODE_ARRAY, NODE_OBJECT, NODE_VALUE
		} NodeType;

		typedef enum 
		{ 
			VALUE_BOOL, VALUE_DOUBLE, VALUE_INT, VALUE_STRING, VALUE_UINT 
		} ValueType;

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////

		explicit JsonTree();
		JsonTree( const JsonTree &jsonTree );
		explicit JsonTree( DataSourceRef dataSource );
        explicit JsonTree( const std::string &key );
        explicit JsonTree( const std::string &key, const bool &value );
        explicit JsonTree( const std::string &key, const double &value );
        explicit JsonTree( const std::string &key, const float &value );
        explicit JsonTree( const std::string &key, const int &value );
        explicit JsonTree( const std::string &key, const std::string &value );
        explicit JsonTree( const std::string &key, const unsigned int &value );
        
		/////////////////////////////////////////////////////////////////////////////////////////////////////////////

		static JsonTree                 createDoc();
		static JsonTree                 parseJson( const std::string &jsonString );

		Iter                            begin();
		ConstIter                       begin() const;
		Iter                            end();
		ConstIter                       end() const;

		JsonTree&                       operator=( const JsonTree &jsonTree );
        
		JsonTree&                       operator[]( const std::string &relativePath );
		const JsonTree&                 operator[]( const std::string &relativePath ) const;
		JsonTree&                       operator[]( uint32_t index );
		const JsonTree&                 operator[]( uint32_t index ) const;
		friend std::ostream&            operator<<( std::ostream &out, const JsonTree &json );

		JsonTree&                       getChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' );
		const JsonTree&                 getChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' ) const;
		JsonTree&                       getChild( uint32_t index );
		const JsonTree&                 getChild( uint32_t index ) const;
		std::vector<JsonTree>&          getChildren();
		const std::vector<JsonTree>&	getChildren() const;

		std::string&                    getKey();
		const std::string&              getKey() const;
		
		std::string                     getPath( char separator = '.' ) const;
		
		NodeType&                       getNodeType();
		const NodeType&                 getNodeType() const;
		ValueType&                      getValueType();
		const ValueType&                getValueType() const;

		bool                            hasChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' );
		bool                            hasChild( const std::string &relativePath, bool caseSensitive = false, char separator = '.' ) const;
		bool                            hasChildren();
		bool                            hasChildren() const;

		JsonTree&						getParent();
		const JsonTree&					getParent() const;
		bool							hasParent();
		bool							hasParent() const;

		void                            push_back( const JsonTree &newChild );
		void							setValue( const std::string &value );
		void							setValueType( ValueType valueType );
		
		void                            write( const fs::path &path, bool createDocument = true );
		void                            write( DataTargetRef target, bool createDocument = true );

		template <typename T> 
		inline T                        getValue()
		{
			try {
				return fromString<T>( mValue );
			} catch ( boost::bad_lexical_cast &) {
				throw ExcNonConvertible( * this );
			}
			return (T)0; // Unreachable. Prevents warning.
		}

		template <typename T> 
		inline T                        getValue() const
		{
			try {
				return fromString<T>( mValue );
			} catch ( boost::bad_lexical_cast &) {
				throw ExcNonConvertible( * this );
			}
			return (T)0; // Unreachable. Prevents warning.
		}

	private:

		explicit JsonTree( const std::string &key, const Json::Value &value );
		explicit JsonTree( const Json::Value &value );

		static Json::Value              deserialize( const std::string &jsonString );
		static std::string              serialize( const Json::Value &value );
		
		Json::Value                     createNativeDoc() const;
		void                            init( const std::string &key, const Json::Value &value, bool setType = false, 
			NodeType nodeType = NODE_VALUE, ValueType valueType = VALUE_STRING );
		
		JsonTree*                       getNodePtr( const std::string &relativePath, bool caseSensitive, char separator ) const;
		static bool                     isIndex( const std::string &key );
		
		std::vector<JsonTree>			mChildren;
		std::string                     mKey;
		JsonTree						*mParent;
		NodeType                        mNodeType;
		std::string                     mValue;
		ValueType                       mValueType;

	public:

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////

		class Exception : public cinder::Exception 
		{
		};

		class ExcChildNotFound : public JsonTree::Exception 
		{

		public:

			ExcChildNotFound( const JsonTree &node, const std::string &key ) throw();
			virtual const char* what() const throw() 
			{ 
				return mMessage; 
			}

		private:

			char mMessage[ 2048 ];

		};

		class ExcNonConvertible : public JsonTree::Exception 
		{

		public:

			ExcNonConvertible( const JsonTree &node ) throw();
			virtual const char* what() const throw() 
			{ 
				return mMessage; 
			}

		private:

			char mMessage[ 2048 ];

		};

		class ExcJsonParserError : public JsonTree::Exception 
		{
		};

	};

	std::ostream&					operator<<( std::ostream &out, const JsonTree &json );

}
